package net.kazed.nextaction.database.serialize;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BackupSummaryRootHandler extends AbstractElementHandler {
    
    private ElementCountHandler contextHandler;
    private ElementCountHandler taskHandler;
    private DateHandler createDateHandler;
    
    public BackupSummaryRootHandler() {
        super();
        contextHandler = new ElementCountHandler();
        taskHandler = new ElementCountHandler();
        createDateHandler = new DateHandler(new SimpleDateFormat("yyyy-MM-dd-HH:mm"));

        addElementHandler("nextaction", this);
        addElementHandler("context", contextHandler);
        addElementHandler("task", taskHandler);
        addElementHandler("createdDate", createDateHandler);
    }

    /**
     * @return Summary of backup file contents.
     */
    public BackupFileSummary getBackupFileSummary() {
        return new BackupFileSummary(createDateHandler.getDate(), contextHandler.getCount(), taskHandler.getCount());
    }
    
    /**
     * @return Number of contexts.
     */
    public int getContextCount() {
        return contextHandler.getCount();
    }
    
    /**
     * @return Number of tasks.
     */
    public int getTaskCount() {
        return taskHandler.getCount();
    }
    
    private class ElementCountHandler extends AbstractElementHandler {
        private int count;

        @Override
        public void endElement(String name, ParserState state) {
            count++;
        }

        /**
         * @return Number of elements counted.
         */
        public int getCount() {
            return count;
        }
    }

    private class DateHandler extends AbstractElementHandler {

        private DateFormat dateFormat;
        private Date date;
        
        /**
         * Constructor.
         * @param dateFormat Date format.
         */
        public DateHandler(DateFormat dateFormat) {
            super();
            this.dateFormat = dateFormat;
        }

        @Override
        public void characters(String text, ParserState state) {
            try {
                date = dateFormat.parse(text);
            } catch (ParseException e) {
                // ignore invalid date
            }
        }

        @Override
        public boolean isValueEncoded() {
            return true;
        }
        
        /**
         * @return Parsed date.
         */
        public Date getDate() {
            return date;
        }
    }

}
